package com.hhkj.admin.invoice.service.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hhkj.admin.invoice.common.cont.InvoiceConst;
import com.hhkj.admin.invoice.domain.Invoice;
import com.hhkj.admin.invoice.model.dopo.InvoiceDo;
import com.hhkj.admin.invoice.model.dopo.InvoicePo;
import com.hhkj.admin.invoice.model.req.InvoiceReq;
import com.hhkj.admin.invoice.model.res.InvoiceRes;
import com.hhkj.admin.invoice.service.base.InvoiceService;
import com.hhkj.admin.invoice.service.biz.InvoiceBizService;
import com.hhkj.admin.invoice.service.extend.InvoiceExtendService;
import com.hhkj.admin.order.common.component.validator.OrderValidator;
import com.hhkj.admin.order.domain.Order;
import com.hhkj.admin.order.service.extend.OrderExtendService;
import com.hhkj.admin.sale.common.cont.SaleCommissionConst;
import com.hhkj.admin.sale.model.dopo.SaleCommissionPo;
import com.ruoyi.common.base.biz.service.biz.BaseBizServiceImpl;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.excl.model.ExcelCreateModel;
import com.ruoyi.common.utils.excl.utils.ExcelUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class InvoiceBizServiceImpl extends BaseBizServiceImpl<Invoice, InvoiceReq, InvoiceRes, InvoiceDo, InvoicePo, InvoiceService, InvoiceExtendService> implements InvoiceBizService {

    @Autowired
    private OrderExtendService orderExtendService;

    @Override
    protected void beforeSave(InvoiceReq invoiceReq) {
        if (getService().hasApplied(invoiceReq.getOrderId())) {
            throw new GlobalException("该订单已经有正在申请中或已经有效的发票了");
        }
        if (InvoiceConst.TitleTypeCode.ENTERPRISE.getCode().equals(invoiceReq.getTitleTypeCode())) {
            if (ObjectUtil.isEmpty(invoiceReq.getTaxIdentificationNumber())) {
                throw new GlobalException("企业发票，纳税识别号不能为空");
            }
        }
        //校验订单是否存在
        Order order = orderExtendService.getByIdNotNull(invoiceReq.getOrderId());
        //校验订单是否已经支付
        OrderValidator.isPaidOrder(order);
        //校验订单是否处理退款流程中
        OrderValidator.isNotRefundingOrder(order);
        //保存发票信息
        invoiceReq.setSaleId(order.getSaleId());
        invoiceReq.setOrderNum(order.getNum());
        invoiceReq.setPrice(order.getFinalPrice());
        invoiceReq.setTypeCode(InvoiceConst.TypeCode.ORDINARY_ELECTRONIC.getCode());
        invoiceReq.setStatusCode(InvoiceConst.Status.NON.getCode());
        super.beforeSave(invoiceReq);
    }

    @Override
    public Workbook createExportWorkbook(InvoiceReq invoiceReq) {
        List<InvoiceRes> list = this.list(invoiceReq);
        String suffix = "";
        if (ObjectUtil.isNotEmpty(invoiceReq.getInvoicingDateStart()) && ObjectUtil.isNotEmpty(invoiceReq.getInvoicingDateEnd())) {
            suffix = " 开票日期：" + DateUtil.format(invoiceReq.getInvoicingDateStart(), "yyyy-MM-dd") + " - " + DateUtil.format(invoiceReq.getInvoicingDateEnd(), "yyyy-MM-dd");
        }
        Workbook template = ExcelUtils.createExcelWorkbookSheetNumber(new ExcelCreateModel(
                SaleCommissionConst.EXPORT_EXCEL_TITLE,
                SaleCommissionConst.EXPORT_EXCEL_TITLE + suffix,
                list,
                InvoiceRes.class));
        return template;
    }

    @Override
    public boolean invoicing(InvoiceReq invoiceReq) {
        invoiceReq.setStatusCode(InvoiceConst.Status.EFFECTIVE.getCode());
        invoiceReq.setInvoicingDate(new Date());
        return this.update(invoiceReq);
    }

    @Override
    public boolean discard(Long id) {
        Invoice invoice = new Invoice();
        invoice.setId(id);
        invoice.setStatusCode(InvoiceConst.Status.INVALID.getCode());
        invoice.setInvalidTime(new Date());
        return this.getService().updateById(invoice);
    }

    @Override
    @Transactional
    public boolean reapply(Long id) {
        Invoice invoice = this.getExtendService().getByIdNotNull(id);
        if (InvoiceConst.Status.INVALID.getCode().equals(invoice.getStatusCode()) == false) {
            throw new GlobalException("当前发票不属于可以重新申请的状态，请检查");
        }
        invoice.setStatusCode(InvoiceConst.Status.REAPPLIED.getCode());
        this.getService().updateById(invoice);
        invoice.setStatusCode(InvoiceConst.Status.NON.getCode());
        invoice.setId(null);
        invoice.setInvoiceNumber(null);
        invoice.setInvoiceUrl(null);
        invoice.setInvoicingDate(null);
        InvoiceReq invoiceReq = BeanUtil.toBean(invoice, InvoiceReq.class);
        return this.save(invoiceReq);
    }
}
